package com.example.ordersystem.utils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ordersystem.R;
import com.example.ordersystem.pojo.Food;

import java.util.List;

//适配器展示菜单列表
public class FoodAdapter extends ArrayAdapter {

    private final int resourceId;
    private boolean isLogin = false;

    public FoodAdapter(Context context, int textViewResourceId, List<Food> listItems) {
        super(context, textViewResourceId, listItems);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Food food = (Food) getItem(position); // 获取当前项的Food实例
        View view = LayoutInflater.from(getContext()).inflate(resourceId, null);//实例化一个对象
        ImageView foodImage = view.findViewById(R.id.food_image);//食物图片
        final TextView foodName = view.findViewById(R.id.food_name);//食物名
        TextView foodMessage = view.findViewById(R.id.food_message);//食物的描述
        TextView foodPrice = view.findViewById(R.id.food_price);//食物的价钱
        Button btn_like = view.findViewById(R.id.btn_like);//收藏按钮
        Button btn_order = view.findViewById(R.id.btn_order);//加入订单按钮

        foodImage.setImageResource(food.getImageId());
        foodName.setText("菜品名：" + food.getFoodName());
        foodMessage.setText("菜品介绍：" + food.getMessage());
        foodPrice.setText("单价：" + food.getPrice() + "元");

        final String userName = ListDataSave.getUserLogin(getContext());
        if (!userName.equals("LoginOut")) {
            isLogin = true;
        } else isLogin = false;

        btn_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isLogin) {
                    boolean b = Like_Food.addFood(food);
                    if (b) {
                        Toast.makeText(getContext(), "收藏了", Toast.LENGTH_SHORT).show();
                    } else Toast.makeText(getContext(), "切勿重复收藏", Toast.LENGTH_SHORT).show();
                } else Toast.makeText(getContext(), "用户尚未登录", Toast.LENGTH_SHORT).show();

            }
        });

        btn_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isLogin) {
                    Order_Food.addFood(food);
                    Toast.makeText(getContext(), "已加入订单", Toast.LENGTH_SHORT).show();
                } else Toast.makeText(getContext(), "用户尚未登录", Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}
